package com.ly.hotel.view.fragments.music;

import java.util.List;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;

import com.ly.hotel.R;
import com.ly.hotel.model.MusicBean;
import com.ly.hotel.msgevent.MusicPlayerEvent;

import de.greenrobot.event.EventBus;

/**
 * @author jouson
 * 正在播放的列表Adapter
 * 包含歌名和移除按钮
 */
public class MusicPlayListAdapter extends BaseAdapter {
	MusicActivity mContext;
	LayoutInflater mInflater;
	private List<MusicBean> playList;

	public MusicPlayListAdapter(MusicActivity c) {
		mContext = c;
		mInflater = LayoutInflater.from(mContext);
	}

	@Override
	public int getCount() {
		return playList.size();
	}

	@Override
	public Object getItem(int postion) {
		return playList.get(postion);
	}

	@Override
	public long getItemId(int postion) {
		return postion;
	}

	@Override
	public View getView(int position, View contentView, ViewGroup arg2) {
		// TODO Auto-generated method stub
		final int pos = position;
		MusicPlayListViewHolder holder;

		if(playList == null){
			return null;
		}
		if (contentView == null) {

			holder = new MusicPlayListViewHolder();
			contentView = mInflater.inflate(R.layout.music_play_list_item, null);
			holder.mbtn = (Button) contentView.findViewById(R.id.m_music_album_music_list_btn);

			holder.mdel = (ImageButton) contentView.findViewById(R.id.m_music_album_music_list_add_btn);


		} else {
			holder = (MusicPlayListViewHolder) contentView.getTag();
		}

		holder.mbtn.setText(playList.get(position).getName());

		holder.mdel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				MusicPlayerEvent e =new MusicPlayerEvent();
				e.setCtlCode(0);
				e.setIndex(pos);
				EventBus.getDefault().post(e);
			}
		});


		holder.mbtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mContext.playerMusicFromPlayList(pos);
			}
		});

		contentView.setTag(holder);

		return contentView;
	}


	/*数据源的更新，每次notifyDataSetChanged之前，都需要更新一下，确保数据的一致性，否则有可能更新失败*/
	public void setDateList(List<MusicBean> playList){
		this.playList = playList;
	}

	static class MusicPlayListViewHolder {
		Button mbtn;//歌名的按钮
		ImageButton mdel;//删除按钮
	}
}
